package com.keur.money.ui.market.act

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.keur.money.R
import com.keur.money.app.MyApp
import com.keur.money.base.utils.DensityUtils
import com.keur.money.base.utils.ImageUtil
import com.keur.money.config.KeurConfigs
import com.keur.money.databinding.ActMullaOrderDetailsBinding
import com.keur.money.http.HttpHelper
import com.keur.money.mvp.MvpAct
import com.keur.money.ui.market.adapter.KeurOrderDetailsAccountAdapter
import com.keur.money.ui.market.impl.KeurOrderDetailsPresenterImpl
import com.keur.money.ui.market.view.IKeurOrderDetailsView
import com.keur.money.ui.user.act.KeurUserLoginAct
import com.keur.money.utils.decoration.LinearSpacingItemDecoration
import com.keur.money.utils.dialog.BindCardAddDialog
import com.keur.money.utils.dialog.BindCardOtherDialog
import com.keur.money.utils.dialog.NoticeDialog
import com.keur.money.utils.dialog.UserDataClearDialog
import com.keur.money.utils.event.KeurEventData
import com.keur.money.utils.event.KeurEventType
import com.keur.money.utils.helper.KeurCustomConfigsHelper
import com.keur.money.utils.helper.SharedHelper
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/8/7 14:01
 * @Annotation：贷款详情
 */
class KeurOrderDetailsAct: MvpAct<IKeurOrderDetailsView, KeurOrderDetailsPresenterImpl>(),IKeurOrderDetailsView {
    lateinit var binding: ActMullaOrderDetailsBinding

    //账户列表
    private var accountAdapter: KeurOrderDetailsAccountAdapter? = null
    //埋点备注
    var eventRemark = ""

    companion object {
        private const val INTENT_KEY_LOGO = "logo"
        private const val INTENT_KEY_PRODUCT = "product"
        private const val INTENT_KEY_TOKEN = "token"
        private const val INTENT_KEY_TITLE = "title"
        fun start(context: Context,pLogo: String, pName: String, pToken: String,pTitle: String) {
            val intent = Intent(context, KeurOrderDetailsAct::class.java)
            intent.putExtra(INTENT_KEY_LOGO, pLogo)
            intent.putExtra(INTENT_KEY_PRODUCT, pName)
            intent.putExtra(INTENT_KEY_TOKEN, pToken)
            intent.putExtra(INTENT_KEY_TITLE, pTitle)
            context.startActivity(intent)
        }
    }

    override fun createPresenter(): KeurOrderDetailsPresenterImpl {
        return KeurOrderDetailsPresenterImpl(this)
    }

    override fun getMullaRootView(): View {
        binding = ActMullaOrderDetailsBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initMullaView() {
        setMullaTitleBarVisibility(View.VISIBLE)
        setMullaTitleBarColor(Color.parseColor("#FFFFFFFF"))
        setMullaBackBtnRes(R.mipmap.mulla_back_black)
        setMullaRightBtnRes(R.mipmap.mulla_kefu_icon)
        setMullaTextTitle(getString(R.string.order_status_title))

        initMullaRefreshLayout()
        initMullaRecyclerViews()
        binding.parentLayout.visibility = View.GONE
        binding.walletLayout.visibility = View.GONE
        binding.btnOk.visibility = View.GONE
        binding.textApplyTips.visibility = View.GONE
        binding.btnClearData.visibility = View.GONE
    }

    override fun initMullaListener() {
        //客服
        rootViewBinding.ivFun.setOnClickListener {
            showMullaKefuDialog(eventRemark,loadProductName(),loadProductToken())
            HttpHelper.addKeurEventAction(KeurEventType.CLICK.KEUR_CLICK_CUSTOMER,eventRemark)
        }
        //去申请
        binding.btnOk.setOnClickListener {
            MyApp.app.publisher.publish(KeurEventData(KeurEventData.TYPE.KEUR_SHOW_HOME))
            MyApp.app.publisher.publish(KeurEventData(KeurEventData.TYPE.KEUR_SHOW_PRODUCTS))
            finish()
        }

        //添加账户
        binding.addLayout.setOnClickListener {
            showMullaBinCardAddDialog()
        }

        //清除用户数据
        binding.btnClearData.setOnClickListener {
            showMullaClearDataDialog()
        }
    }

    override fun initMullaData() {
        showMullaLoading(isTOuchOut = false, isCancel = true)
        presenter.loadMullaOrderStatusAction()

        //牌照信息
        val licenseInfo = KeurCustomConfigsHelper.getMullaLicenseInfo()
        if (licenseInfo == null){
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.visibility = View.GONE
        } else {
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.addView(licenseView())
            binding.licenseLayout.visibility = View.VISIBLE
        }
    }


    /* 初始化刷新 */
    private fun initMullaRefreshLayout() {
        //禁止加载
        binding.refreshLayout.setEnableLoadMore(false)
        binding.refreshLayout.setEnableAutoLoadMore(false)
        binding.refreshLayout.setOnRefreshListener {
            presenter.loadMullaOrderStatusAction()
        }
        binding.refreshLayout.setOnLoadMoreListener {
            binding.refreshLayout.finishLoadMore()
        }
    }

    /**
     * 初始化Views
     */
    private fun initMullaRecyclerViews(){
        binding.recyclerView.isNestedScrollingEnabled = false
        binding.recyclerView.isFocusableInTouchMode = false //不需要焦点
        val topDecoration = DensityUtils.dp2px(12f)
        binding.recyclerView.addItemDecoration(LinearSpacingItemDecoration(0, 0, 0, topDecoration))
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = RecyclerView.VERTICAL
        binding.recyclerView.layoutManager = layoutManager
        accountAdapter = KeurOrderDetailsAccountAdapter(binding.recyclerView)
        binding.recyclerView.adapter = accountAdapter
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
        accountAdapter?.setOnItemChildClickListener { _, childView, position ->
            val item = accountAdapter?.getItem(position)
            when(childView.id){
                R.id.imgDelete -> {//删除

                }
            }
        }
    }

    /**
     * 产品Logo
     */
    private fun loadProductLogo(): String{
        return intent.extras?.getString(INTENT_KEY_LOGO).toString()
    }

    /**
     * 获取查看的产品名称
     */
    override fun loadProductName(): String {
        return intent.extras?.getString(INTENT_KEY_PRODUCT).toString()
    }

    /**
     * 获取查看的产品Token
     */
    override fun loadProductToken(): String {
        return intent.extras?.getString(INTENT_KEY_TOKEN).toString()
    }

    /**
     * 获取产品Title
     */
    private fun loadProductTitle(): String {
        return intent.extras?.getString(INTENT_KEY_TITLE).toString()
    }

    /**
     * 共用Views
     */
    @SuppressLint("SetTextI18n")
    override fun showMullaOrderCommonViews(obj: JSONObject) {
        binding.parentLayout.visibility = View.VISIBLE
        ImageUtil.instance?.loadImageUrl(this,binding.imgLogo,loadProductLogo(), R.mipmap.icon_holder)
        binding.textName.text = loadProductTitle()
        binding.textAmount.text = "${obj.optString("currency")} ${obj.optString("amount")}"
        binding.textTerm.text = String.format(getString(R.string.order_term_value),obj.optString("days"))
    }

    /**
     * 审核中
     */
    override fun showMullaOrderAuditViews(obj: JSONObject) {
        binding.imgStatusIcon.setImageResource(R.mipmap.mulla_order_details_audit_icon)

        val showKey = getString(R.string.order_details_audit_tips_key)
        val showText = String.format(getString(R.string.order_details_audit_tips),showKey)
        val startIndex = showText.indexOf(showKey)

        val spString = SpannableString(showText)
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#FF8027FF")), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textStatusTips.text = spString

        binding.walletLayout.visibility = View.GONE
        binding.btnOk.visibility = View.VISIBLE
        binding.textApplyTips.visibility = View.VISIBLE
        binding.btnClearData.visibility = View.GONE

        //根据配置显示公告信息
        showMullaNoticeDialog()
        //需要调用评分接口
        presenter.loadMullaScoreCommentAction()
    }

    /**
     * 放款中
     */
    override fun showMullaOrderLendingViews(obj: JSONObject) {
        binding.imgStatusIcon.setImageResource(R.mipmap.mulla_order_details_lending_icon)

        val showKey = getString(R.string.order_details_lending_tips_key)
        val showText = String.format(getString(R.string.order_details_lending_tips),showKey)
        val startIndex = showText.indexOf(showKey)

        val spString = SpannableString(showText)
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#FF14B8A6")), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textStatusTips.text = spString

        binding.walletLayout.visibility = View.VISIBLE
        binding.btnOk.visibility = View.GONE
        binding.textApplyTips.visibility = View.GONE
        binding.btnClearData.visibility = View.GONE


        //根据配置显示公告信息
        showMullaNoticeDialog()
        //需要显示账户列表
        presenter.loadMullaAccountListAction()
        //需要调用评分接口
        presenter.loadMullaScoreCommentAction()

        binding.addLayout.visibility = View.GONE
        //法语地区显示添加账户按钮
        if (KeurConfigs.isFrench()){
            binding.addLayout.visibility = View.VISIBLE
            //积分
            binding.textPoints.text = String.format(getString(R.string.step_phonebook_add_points),KeurCustomConfigsHelper.getMullaAddAccountPoints())
        }
    }

    /**
     * 已拒绝
     */
    override fun showMullaOrderRejectedViews(obj: JSONObject) {
        binding.imgStatusIcon.setImageResource(R.mipmap.mulla_order_details_rejected_icon)

        val showKey = String.format(getString(R.string.order_details_rejected_tips_key),obj.optString("againApplyDate"))
        val showText = String.format(getString(R.string.order_details_rejected_tips),loadProductTitle(),showKey)
        val startIndex = showText.indexOf(showKey)

        val spString = SpannableString(showText)
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#FFFFAC25")), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textStatusTips.text = spString

        binding.walletLayout.visibility = View.GONE
        binding.btnOk.visibility = View.GONE
        binding.textApplyTips.visibility = View.GONE
        binding.btnClearData.visibility = View.GONE

        //审核被拒绝需要需要调接口判断是否显示清除用户数据按钮
        presenter?.loadMullaUserClearDataAction(true)
    }

    /**
     * 待还款
     */
    override fun showMullaOrderRepayViews(obj: JSONObject) {
        //刷新产品列表
        MyApp.app.publisher.publish(KeurEventData(KeurEventData.TYPE.KEUR_PRODUCT_REFRESH))
        //跳转到待还款页面
        KeurRepayAct.start(this,loadProductName(),loadProductToken())
        Handler(Looper.getMainLooper()).postDelayed({ finish() },1000)
    }

    /**
     * 收款账户列表
     */
    override fun showMullaAccountList(accountList: ArrayList<JSONObject>) {
        accountAdapter?.data = accountList

        accountAdapter?.let {
            //最多添加10个账户
            if (it.itemCount >= 10){
                binding.addLayout.isEnabled = false
                binding.addLayout.setBackgroundResource(R.drawable.mulla_btn_disabled_12)
            } else {
                binding.addLayout.isEnabled = true
                binding.addLayout.setBackgroundResource(R.drawable.mulla_btn_pressed_12)
            }
        }
    }

    /**
     * 是否显示清除用户数据按钮
     */
    override fun showMullaClearDataBtn(isShow: Boolean) {
        when(isShow){
            true -> {
                binding.btnClearData.visibility = View.VISIBLE
            }
            else -> {
                binding.btnClearData.visibility = View.GONE
            }
        }
    }

    /**
     * 清除用户数据成功，需要打开登录页面
     */
    override fun showMullaClearDataSuccess() {
        //退出登录，需要移除用户保存的信息
        SharedHelper.onKeurLoginOut()
        onIntent(KeurUserLoginAct::class.java)
    }

    /**
     * 添加绑卡dialog
     */
    private fun showMullaBinCardAddDialog(){
        HttpHelper.addKeurEventAction(KeurEventType.CLICK.KEUR_CLICK_USER_ACCOUNT_ADD,eventRemark)
        val bindCardDialog = BindCardAddDialog(this,eventRemark,object : BindCardAddDialog.IDialogCallback{
            override fun onClick(view: View?) {
            }
            override fun onSubmitParams(typeObj: JSONObject, phoneNumber: String) {
                presenter.submitMullaBindAccountAction(phoneNumber,typeObj.optString("value"))
            }
        })
        bindCardDialog.setCancelable(true)
        bindCardDialog.setCanceledOnTouchOutside(true)
        bindCardDialog.show()
    }

    /**
     * 提示绑定另一个渠道账户
     */
    override fun showMullaBingAccountOtherDialog(otherInfo: JSONObject) {
        val replaceDialog = BindCardOtherDialog(this,eventRemark,object : BindCardOtherDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view?.id == R.id.btnRight){//添加
                    presenter.submitMullaBindAccountAction(otherInfo.optString("walletMobile"),otherInfo.optString("value"), "YES")
                }
            }
        })
        replaceDialog.setCancelable(true)
        replaceDialog.setCanceledOnTouchOutside(false)
        replaceDialog.show()
        replaceDialog.setBindAccountInfo(otherInfo)
    }

    /**
     * 审核中、放款中 根据配置显示公告Dialog
     */
    private fun showMullaNoticeDialog(){
        if (!KeurCustomConfigsHelper.isMullaAuditNotice()){
            return
        }

        val noticeInfo = KeurCustomConfigsHelper.getMullaAuditNoticeInfo() ?: return
        val showNum = noticeInfo.optInt("num",1)
        val completeNum = SharedHelper.getKeurSPInt(SharedHelper.KEUR_SPKEY.KEUR_DIALOG_NOTICE_NUM)
        //本地记录的显示公告次数 >= 配置次数
        if (completeNum >= showNum){
            return
        }

        SharedHelper.saveKeurSPData(SharedHelper.KEUR_SPKEY.KEUR_DIALOG_NOTICE_NUM,completeNum+1)
        val noticeDialog = NoticeDialog(this,object : NoticeDialog.IDialogCallback{
            override fun onClick(view: View?) {
            }
        })
        noticeDialog.show()
        noticeDialog.setTipsTitle(noticeInfo.optString("noticeTitle"))
        noticeDialog.setTips(noticeInfo.optString("noticeText"))
    }

    /**
     * 清空用户数据dialog
     */
    private fun showMullaClearDataDialog(){
        val clearDialog = UserDataClearDialog(this,object : UserDataClearDialog.IDialogCallback{
            override fun onMullaConfirmClick() {
                showMullaLoading()
                presenter?.loadMullaUserClearDataAction(false)
            }
        })
        clearDialog.setCancelable(true)
        clearDialog.setCanceledOnTouchOutside(true)
        clearDialog.show()
    }

    override fun hideMullaLoading() {
        super.hideMullaLoading()
        binding.refreshLayout.finishRefresh()
    }

    override fun onStart() {
        super.onStart()
        eventRemark = "${loadProductName()} Details Page"
        HttpHelper.addKeurEventAction(KeurEventType.PAGE.KEUR_PAGE_ORDER_DETAILS_START,eventRemark)
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addKeurEventAction(KeurEventType.PAGE.KEUR_PAGE_ORDER_DETAILS_END,eventRemark)
    }
}